package ex4.multiThread.mutiThreadSorter;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

class SortThread implements Runnable{
	int[] numbers;
	int left;
	int right;
	SortThread(int left,int right,int[] numbers){
		this.left=left;
		this.right=right;
		this.numbers=numbers;
	}
	public synchronized void run(){
//		for(int i=left;i<right;i++) {
//			System.out.print(numbers[i]+" ");
//		}
//		System.out.println();
		for(int i=left;i<right;i++) {
			for(int j=left;j<right;j++) {
				if(numbers[j]>numbers[j+1]) {
					int temp=numbers[j];
					numbers[j]=numbers[j+1];
					numbers[j+1]=temp;
				}
			}
		}
//		for(int i=left;i<right;i++) {
//			System.out.print(numbers[i]+" ");
//		}
//		System.out.println();
		System.out.printf("[%s]:完成%d到%d的排序\n",Thread.currentThread().getName(),left,right);
	}
}
public class Sorter {
	public static void main(String[] args) {
		Random random=new Random();
		int number=10000;
		int divide=number/2;
		System.out.println(number);
		int[] numbers=new int[number];
		int[] numberss=new int[number];
		for(int i=0;i<number;i++) {
			//numbers[i]=random.nextInt(100);
			numbers[i]=(int)(Math.random()*1000);
			//System.out.println(numbers[i]);
		}	
		System.out.println("Orginal:"+Arrays.toString(numbers));
		
		Thread t0=new Thread(new SortThread(0,divide,numbers));
		Thread t1=new Thread(new SortThread(divide+1,number-1,numbers));
		t0.start();
		t1.start();
		while(t0.isAlive()||t1.isAlive()) {
		}
	//当测试数据值偏大时，这种方式输出不显示？
//		System.out.print("SubSorted:");
//		for(int i=0;i<number;i++) {
//			System.out.print(numbers[i]+" ");
//		}
//		System.out.println();
		for(int i=0,j=0,k=divide+1;i<number;) {
			while(j<=divide&&k<=number-1) {
				int temp;
				if(numbers[j]<=numbers[k]) temp=numbers[j++];
				else temp=numbers[k++];
				numberss[i++]=temp;
			}
			while(j<=divide) {
				numberss[i++]=numbers[j++];
			}
			while(k<=number-1) {
				numberss[i++]=numbers[k++];
			}
		}
		System.out.println("Sorted:"+Arrays.toString(numberss));
		
	}
}